package com.atguigu.sso_server.controller;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseCookie;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

@Controller
public class LoginController {
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @GetMapping("/login.html")
    public String loginHtml(Model model, @CookieValue(value = "sso_token",required = false)String sso_token, @RequestParam(value = "redirectUrl",required = false)String redirectUrl){
        if(!StringUtils.isEmpty(sso_token)){
            return "redirect:"+redirectUrl+"?token="+sso_token;
        }
        model.addAttribute("redirectUrl",redirectUrl);
        return "login";
    }

    @GetMapping("/redisUserName")
    @ResponseBody
    public String redisUserName(String token){
        String loginUser = stringRedisTemplate.opsForValue().get(token);
        return loginUser;
    }


    @PostMapping("/sso/login")
    public String ssoLogin(String username, String password, @RequestParam(value ="redirectUrl",required = false ) String redirectUrl, HttpServletResponse response){
        if(!StringUtils.isEmpty(username) && !StringUtils.isEmpty(password)){
            String uuid = UUID.randomUUID().toString().replace("-", "");
            stringRedisTemplate.opsForValue().set(uuid,username);
            ResponseCookie responseCookie= ResponseCookie.from("sso_token",uuid).domain("ssoserver.com").secure(false).path("/").sameSite("None").build();
            response.setHeader(HttpHeaders.SET_COOKIE, responseCookie.toString());
            return "redirect:"+redirectUrl+"?token="+uuid;
        }
        return "login";
    }
}
